package com.baizhi.serviceimpl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baizhi.annotation.AddCache;
import com.baizhi.annotation.AddLog;
import com.baizhi.annotation.DelCache;
import com.baizhi.dao.UserMapper;
import com.baizhi.entity.User;
import com.baizhi.entity.UserExample;
import com.baizhi.service.UserService;
import com.baizhi.util.ALiyunOSSUtil;
import com.baizhi.util.UUIDUtil;
import com.baizhi.vo.CommonQueryPageVO;
import com.baizhi.vo.CommonVO;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    UserMapper userMapper;
    @Resource
    HttpServletRequest request;

    @Override
    public HashMap<String, Object> queryAllPage(Integer page, Integer pageSize) {

        HashMap<String, Object> map = new HashMap<>();

        //设置当前页
        map.put("page",page);

        //设置查询条件对象
        UserExample example = new UserExample();

        //查询总条数
        int count = userMapper.selectCountByExample(example);

        //设置总条数
        map.put("total",count);

        //创建分页对象  参数：起始条数,数据数
        RowBounds rowBounds = new RowBounds((page-1)*pageSize,pageSize);

        //根据分页查询数据
        List<User> users = userMapper.selectByExampleAndRowBounds(example, rowBounds);

        //设置数据
        map.put("rows",users);

        return map;
    }

    @DelCache
    @AddLog(value = "修改用户")
    @Override
    public HashMap<String, Object> update(User user) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            userMapper.updateByPrimaryKeySelective(user);
            map.put("message","修改成功!!!!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("message","修改失败!!!!");
        }
        return map;
    }

    /*@Override
    public HashMap<String, Object> delete(User user) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            userMapper.delete(user);
            map.put("message","删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("message","删除失败");
        }
        return map;
    }*/

    @AddCache
    @Override
    public CommonQueryPageVO queryAllPages(Integer page, Integer pageSize) {

        //设置查询条件对象
        UserExample example = new UserExample();

        //查询总条数
        int total = userMapper.selectCountByExample(example);

        //创建分页对象  参数：起始条数,数据数
        RowBounds rowBounds = new RowBounds((page-1)*pageSize,pageSize);

        //根据分页查询数据
        List<User> users = userMapper.selectByExampleAndRowBounds(example, rowBounds);

        return new CommonQueryPageVO(page,total,users);
    }

    @DelCache
    @AddLog(value = "修改用户")
    @Override
    public void updates(User user){
        //System.out.println("==执行目标方法===");
        userMapper.updateByPrimaryKeySelective(user);
        //int i=10/0;

        /*try {
            userMapper.updateByPrimaryKeySelective(user);
            int i=10/0;
            return CommonVO.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonVO.faild();
        }*/

        /*try {
            userMapper.update(user);
            //int i=10/0;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("出现异常！！");
        }*/
    }

    @DelCache
    @Override
    public void add(User user) {
        log.info("user service 获取用户信息",user);
        user.setId(UUIDUtil.getUUID());
        //user.setStatus("1");
        //user.setCreateTime(new Date());
        log.info("user service 添加用户信息",user);
        userMapper.insertSelective(user);
    }

    @Override
    public String uploadHeadImg(MultipartFile headImg) {
        //获取文件名
        String filename = headImg.getOriginalFilename();
        String newName = new Date().getTime() + "--" + filename;
        //获取绝对路径
        String realPath = request.getSession().getServletContext().getRealPath("/upload/headImg");
        File file = new File(realPath);
        if(!file.exists()){
            file.mkdirs();
        }
        String message=null;
        //文件上传
        try {
            headImg.transferTo(new File(newName,realPath));
            message="newName";
        } catch (IOException e) {
            e.printStackTrace();
            message="newName";
        }

        return message;
    }

    @Override
    public String uploadHeadImgaliyun(MultipartFile headImg) {
        //获取文件名
        String filename = headImg.getOriginalFilename();
        String newName = new Date().getTime() + "--" + filename;

        String bucketName = "yingx-2111";
        String objectName = "userImg/"+newName;
        //拼接图片的网络地址
        String netPath="https://yingx-2111.oss-cn-beijing.aliyuncs.com/"+objectName;
        String message=null;
        //文件上传
        try {
        ALiyunOSSUtil.uploadfileBytes(bucketName,objectName,headImg);

            message=netPath;
        } catch (Exception e) {
            e.printStackTrace();
            message=netPath;
        }
        return message;
    }

    @AddCache
    @Override
    public User queryById(String id) {

        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void delete(User user) {
        //1.删除文件

        //2.根据id查询文件信息
        User users = userMapper.selectOne(user);
        //4.获取图片网络路径
        String headImg = users.getHeadImg();
        String imgPath = headImg.replace("https://yingx-2111.oss-cn-beijing.aliyuncs.com/","");

        ALiyunOSSUtil.deleteFile("yingx-2111",imgPath);

        //3.删除数据
        userMapper.delete(user);
    }


}
